<template>
  <div class="yoyo-container mx-auto min-h-screen pb-[20px]">
    <!-- 导航栏 -->
    <navBar :title="$t('userInfo.title')"></navBar>
    <!-- 基本信息 -->
    <div class="bg-white mt-2 mx-4 rounded-xl">
      <van-cell-group class="bg-transparent">
        <van-field v-model="baseInfo.nickname" :label="$t('userInfo.name')" :placeholder="$t('userInfo.namePlaceholder')" />
        <van-field
          v-model="baseInfo.sexText"
          :label="$t('userInfo.gender')"
          readonly
          is-link
          :placeholder="$t('userInfo.genderPlaceholder')"
          @click-input="editGender" />
        <van-field
          v-model="baseInfo.birthday"
          :label="$t('userInfo.birthday')"
          readonly
          is-link
          :placeholder="$t('userInfo.birthdayPlaceholder')"
          @click-input="editBirthday" />
        <van-field
          v-model="baseInfo.countryText"
          :label="$t('userInfo.country')"
          :placeholder="$t('userInfo.countryPlaceholder')"
          readonly
          is-link
          @click-input="showCountryPopup = true" />
        <van-field
          v-model="baseInfo.mobile"
          label-width="100px"
          :label="$t('userInfo.phone')"
          :border="false"
          :placeholder="$t('userInfo.phonePlaceholder')" />
      </van-cell-group>

      <van-button v-if="isEdit" type="primary" round color="#ff7a00" class="mx-16 w-[calc(100%-8rem)] my-3" @click="updateBaseInfo">
        {{ $t("userInfo.updateUserInfo") }}
      </van-button>
    </div>

    <!-- 联系信息 -->
    <div class="bg-white mt-2 mx-4 rounded-xl">
      <van-cell-group>
        <!-- 修改密码 -->
        <van-field :label="$t('userInfo.changePassword')" label-width="140px" readonly is-link @click-input="dialogVisible = true" />
        <van-field v-model="baseInfo.email" :label="$t('userInfo.email')" :placeholder="$t('userInfo.emailPlaceholder')" />
      </van-cell-group>
    </div>

    <div class="bg-white mt-2 mx-4 rounded-xl">
      <van-cell :title="$t('userInfo.address')" :border="false" is-link>
        <template #right-icon>
          <van-button type="primary" size="small" round color="#ff7a00" @click.stop="goToAddAddress">
            + {{ $t("userInfo.addAddress") }}
          </van-button>
        </template>
      </van-cell>

      <!-- 地址列表 -->
      <div class="px-4 pb-4">
        <div
          v-for="(address, index) in addresses"
          :key="index"
          class="bg-gray-50 rounded-lg p-3 mb-3 flex justify-between items-start mb-2"
          @click="goToAddAddress(address)">
          <div class="flex-1">
            <div class="font-medium text-gray-800">{{ address.name }} | {{ address.mobile }}</div>
            <div class="text-sm text-gray-600 mt-1">{{ address.country }} {{ address.city }} {{ address.detailAddress }}</div>
          </div>
          <van-button v-if="address.defaultStatus" type="warning" size="mini" round color="#ff7a00" class="w-10">
            {{ $t("userInfo.default") }}
          </van-button>
        </div>
      </div>
    </div>
    <!-- 银行账号/信用卡 -->
    <div class="bg-white mt-2 mx-4 rounded-xl">
      <van-cell :title="$t('userInfo.bankCard')" is-link>
        <template #right-icon>
          <van-button type="primary" size="small" round color="#ff7a00" @click.stop="addBankCard">
            + {{ $t("userInfo.addBankCard") }}
          </van-button>
        </template>
      </van-cell>

      <!-- 银行卡列表 -->
      <div class="px-4 pb-4">
        <div v-for="(card, index) in bankCards" :key="index" class="bg-gray-50 rounded-lg p-3 mb-3">
          <div class="flex justify-between items-start mb-2" @click="goToBankCard(card)">
            <div class="flex-1">
              <div class="font-medium text-gray-800">{{ card.cardNo }}</div>
            </div>
            <van-button v-if="card.defaultStatus" type="warning" size="mini" round color="#ff7a00">
              {{ $t("userInfo.default") }}
            </van-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 性别选择弹窗 -->
    <van-popup v-model="showGenderPopup" position="bottom">
      <van-picker show-toolbar :columns="genderOptions" @confirm="onGenderConfirm" @cancel="showGenderPopup = false" />
    </van-popup>

    <!-- 国家选择弹窗 -->
    <van-popup v-model="showCountryPopup" position="bottom">
      <van-picker show-toolbar :columns="countryOptions" @confirm="onCountryConfirm" @cancel="showCountryPopup = false" />
    </van-popup>

    <!-- 日期选择弹窗 -->
    <van-popup v-model="showDatePopup" position="bottom">
      <van-datetime-picker v-model="selectedDate" type="date" @confirm="onDateConfirm" @cancel="showDatePopup = false" />
    </van-popup>

    <CommonDialog
      :visible.sync="dialogVisible"
      :title="$t('userInfo.changePassword')"
      :buttons="[{ text: $t('common.confirm'), type: 'primary', action: 'submit' }]"
      @button-click="handleButtonClick"
      @close="handleClose">
      <div class="text-center">
        <div class="mb-4">
          <input
            v-model="password"
            type="text"
            :placeholder="$t('userInfo.passwordPlaceholder')"
            class="w-full h-12 px-4 border border-gray-200 rounded-lg text-sm" />
        </div>
      </div>
    </CommonDialog>
  </div>
</template>

<script>
import { NavBar, Cell, CellGroup, Button, Popup, Field, Picker, DatetimePicker } from "vant"
import { changePassword, getBaseInfo, updateBaseInfo, getAddresses, getCountryList, getBankList } from "@/apis/userInfo"

import { mapActions, mapGetters } from "vuex"

export default {
  name: "UserInfo",
  components: {
    [NavBar.name]: NavBar,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Field.name]: Field,
    [Picker.name]: Picker,
    [DatetimePicker.name]: DatetimePicker,
  },
  data() {
    return {
      baseInfo: {
        nickname: "",
        sex: "",
        birthday: "",
        mobile: "",
        email: "",
      },
      baseOriginalInfo: {},
      addresses: [],
      bankCards: [],
      showGenderPopup: false,
      showDatePopup: false,
      showCountryPopup: false,
      editType: "",
      editTitle: "",
      editPlaceholder: "",
      editValue: "",
      selectedDate: new Date(),
      genderOptions: [
        { text: this.$t("userInfo.male"), value: "1" },
        { text: this.$t("userInfo.female"), value: "2" },
      ],
      dialogVisible: false,
      password: "",
      email: "",
      countryOptions: [],
    }
  },
  computed: {
    ...mapGetters({
      isLoggedIn: "auth/isLoggedIn",
      userInfo: "auth/userInfo",
    }),
    isEdit() {
      return (
        this.baseOriginalInfo.nickname !== this.baseInfo.nickname ||
        this.baseOriginalInfo.sex !== this.baseInfo.sex ||
        this.baseOriginalInfo.birthday !== this.baseInfo.birthday ||
        this.baseOriginalInfo.countryId !== this.baseInfo.countryId ||
        this.baseOriginalInfo.mobile !== this.baseInfo.mobile ||
        this.baseOriginalInfo.email !== this.baseInfo.email
      )
    },
  },
  created() {
    this.fetchBaseInfo()
    this.fetchAddresses()
    this.fetchCountryList()
    this.fetchBankList()
  },
  methods: {
    async fetchBaseInfo() {
      try {
        const response = await getBaseInfo()
        const data = response.data
        data.sexText = data.sex - 0 ? (data.sex === 1 ? this.$t("userInfo.male") : this.$t("userInfo.female")) : ""
        this.baseOriginalInfo = { ...data }
        this.baseInfo = data
      } catch (error) {
        console.error("获取用户信息失败:", error)
      }
    },
    async updateBaseInfo() {
      try {
        const response = await updateBaseInfo(this.baseInfo)
        this.baseOriginalInfo = { ...this.baseInfo }
        this.$toast.success(this.$t("userInfo.updateSuccess"))
      } catch (error) {
        console.error("更新用户信息失败:", error)
      }
    },
    async fetchAddresses() {
      try {
        const response = await getAddresses()
        this.addresses = response.data
      } catch (error) {
        console.error("获取地址失败:", error)
      }
    },
    async fetchBankList() {
      try {
        const response = await getBankList()
        this.bankCards = response.data
      } catch (error) {
        console.error("获取银行列表失败:", error)
      }
    },
    async fetchCountryList() {
      try {
        const response = await getCountryList()
        const data = response.data
        this.countryOptions = data.map((item) => {
          return {
            text: this.$store.getters.isZh ? item.name : item.nameEn,
            value: item.id,
          }
        })
      } catch (error) {
        console.error("获取国家列表失败:", error)
      }
    },
    editGender() {
      this.showGenderPopup = true
    },
    editBirthday() {
      this.showDatePopup = true
    },
    goToAddAddress(address) {
      console.log("address :>> ", address)
      this.$router.push({ path: "/address", query: { id: address.id } })
    },
    addBankCard() {
      console.log("新增银行卡")
      this.$router.push({ path: "/bank-card" })
    },
    goToBankCard(card) {
      console.log("goToBankCard :>> ", card)
      this.$router.push({ path: "/bank-card", query: { id: card.id } })
    },
    onGenderConfirm(value) {
      console.log("value :>> ", value)
      this.baseInfo.sexText = value.text
      this.baseInfo.sex = value.value
      this.showGenderPopup = false
    },
    onDateConfirm(value) {
      this.baseInfo.birthday = value.toISOString().split("T")[0]
      this.showDatePopup = false
    },
    onCountryConfirm(value) {
      this.baseInfo.countryText = value.text
      this.baseInfo.countryId = value.value
      this.showCountryPopup = false
    },
    async handleButtonClick() {
      await changePassword({
        password: this.password,
      })
      this.dialogVisible = false
    },
    handleClose() {
      this.dialogVisible = false
    },
  },
  watch: {
    isLoggedIn: {
      handler(newVal) {
        if (newVal && this.$route.path === "/user-info") {
          this.fetchBaseInfo()
          this.fetchAddresses()
          this.fetchCountryList()
        }
      },
      deep: true,
      immediate: false,
    },
  },
}
</script>

<style scoped>
/deep/.van-cell-group {
  background-color: transparent;
}
/deep/.van-cell {
  background-color: transparent;
}
/deep/.van-field__control {
  text-align: right;
}
</style>
